<!-- 登录页面示例 -->
<!-- @/pages/login/login.vue -->

<template>
  <view class="login-container">
    <view class="login-header">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="title">欢迎登录</text>
    </view>

    <view class="login-form">
      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view
          class="tab-item"
          :class="{ active: loginType === 'account' }"
          @click="loginType = 'account'"
        >
          账号密码登录
        </view>
        <view
          class="tab-item"
          :class="{ active: loginType === 'mobile' }"
          @click="loginType = 'mobile'"
        >
          手机验证码登录
        </view>
      </view>

      <!-- 账号密码登录 -->
      <template v-if="loginType === 'account'">
        <view class="form-item">
          <u-input
            v-model="accountForm.username"
            placeholder="请输入用户名"
            prefixIcon="account"
            clearable
            border="surround"
            @confirm="handleLogin"
          />
        </view>
        <view class="form-item">
          <u-input
            v-model="accountForm.password"
            type="password"
            placeholder="请输入密码"
            prefixIcon="lock"
            clearable
            border="surround"
            @confirm="handleLogin"
          />
        </view>
        <view class="form-item" v-if="showCaptcha">
          <u-input
            v-model="accountForm.captcha"
            placeholder="请输入验证码"
            border="surround"
            @confirm="handleLogin"
          >
            <template #suffix>
              <image 
                class="captcha-img" 
                :src="captchaUrl" 
                @click="refreshCaptcha"
              />
            </template>
          </u-input>
        </view>
      </template>

      <!-- 手机验证码登录 -->
      <template v-else>
        <view class="form-item">
          <u-input
            v-model="mobileForm.mobile"
            type="number"
            placeholder="请输入手机号"
            prefixIcon="phone"
            clearable
            border="surround"
            maxlength="11"
          />
        </view>
        <view class="form-item">
          <u-input
            v-model="mobileForm.code"
            placeholder="请输入验证码"
            border="surround"
            maxlength="6"
            @confirm="handleLogin"
          >
            <template #suffix>
              <u-button
                type="primary"
                size="mini"
                :text="codeText"
                :disabled="codeDisabled"
                @click="sendCode"
              />
            </template>
          </u-input>
        </view>
      </template>

      <!-- 记住我 & 忘记密码 -->
      <view class="form-options">
        <view class="remember-me" @click="rememberMe = !rememberMe">
          <u-checkbox
            v-model="rememberMe"
            shape="circle"
            size="16"
          />
          <text class="remember-text">记住我</text>
        </view>
        <text class="forget-password" @click="handleForgetPassword">
          忘记密码？
        </text>
      </view>

      <!-- 登录按钮 -->
      <view class="form-item">
        <u-button
          type="primary"
          text="登录"
          :loading="loading"
          :disabled="!canLogin"
          @click="handleLogin"
        />
      </view>

      <!-- 其他操作 -->
      <view class="form-footer">
        <text class="register-link" @click="handleRegister">
          还没有账号？立即注册
        </text>
      </view>

      <!-- 第三方登录 -->
      <view class="third-party">
        <view class="divider">
          <text class="divider-text">其他登录方式</text>
        </view>
        <view class="third-party-buttons">
          <view class="third-party-item" @click="handleThirdPartyLogin('wechat')">
            <u-icon name="weixin-circle-fill" color="#07C160" size="40" />
          </view>
          <view class="third-party-item" @click="handleThirdPartyLogin('apple')">
            <u-icon name="apple-fill" color="#000" size="40" />
          </view>
        </view>
      </view>
    </view>

    <!-- Toast -->
    <u-toast ref="uToast" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 临时类型定义
interface LoginParams {
  username: string
  password: string
  captcha?: string
  captchaId?: string
  rememberMe?: boolean
  loginType?: 'account' | 'mobile' | 'email'
}

interface MobileLoginParams {
  mobile: string
  code: string
}

class AuthError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'AuthError'
  }
}

class HttpError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'HttpError'
  }
}

// 临时的模拟实现
const useAuthStore = () => ({
  login: async (params: LoginParams) => {
    console.log('模拟登录:', params)
  },
  mobileLogin: async (params: MobileLoginParams) => {
    console.log('模拟手机登录:', params)
  }
})

const http = {
  post: async (url: string, data: any) => {
    console.log('模拟请求:', url, data)
  },
  baseURL: 'http://localhost:3000'
}

// Hooks
const authStore = useAuthStore()
const uToast = ref()

// 响应式数据
const loginType = ref<'account' | 'mobile'>('account')
const loading = ref(false)
const rememberMe = ref(false)
const showCaptcha = ref(false)
const captchaUrl = ref('')
const captchaId = ref('')

// 账号表单
const accountForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 手机号表单
const mobileForm = reactive({
  mobile: '',
  code: ''
})

// 验证码相关
const codeText = ref('获取验证码')
const codeDisabled = ref(false)
const codeTimer = ref<number>()

// 计算属性
const canLogin = computed(() => {
  if (loginType.value === 'account') {
    return accountForm.username && accountForm.password &&
      (!showCaptcha.value || accountForm.captcha)
  } else {
    return mobileForm.mobile && mobileForm.code
  }
})

// 生命周期
onLoad((options) => {
  // 检查是否有重定向地址
  const redirectUrl = uni.getStorageSync('auth_redirect_url')
  if (redirectUrl) {
    uni.removeStorageSync('auth_redirect_url')
  }
  
  // 初始化
  initLoginForm()
})

onMounted(() => {
  // 恢复记住的账号
  const savedUsername = uni.getStorageSync('saved_username')
  if (savedUsername) {
    accountForm.username = savedUsername
    rememberMe.value = true
  }
})

// 初始化登录表单
const initLoginForm = () => {
  // 检查登录失败次数，显示验证码
  const failCount = uni.getStorageSync('login_fail_count') || 0
  if (failCount >= 3) {
    showCaptcha.value = true
    refreshCaptcha()
  }
}

// 处理登录
const handleLogin = async () => {
  if (!canLogin.value || loading.value) return
  
  loading.value = true
  
  try {
    if (loginType.value === 'account') {
      // 账号密码登录
      const params: LoginParams = {
        username: accountForm.username,
        password: accountForm.password,
        rememberMe: rememberMe.value,
        loginType: 'account'
      }
      
      if (showCaptcha.value) {
        params.captcha = accountForm.captcha
        params.captchaId = captchaId.value
      }
      
      await authStore.login(params)
      
      // 记住用户名
      if (rememberMe.value) {
        uni.setStorageSync('saved_username', accountForm.username)
      } else {
        uni.removeStorageSync('saved_username')
      }
    } else {
      // 手机验证码登录
      const params: MobileLoginParams = {
        mobile: mobileForm.mobile,
        code: mobileForm.code
      }
      
      await authStore.mobileLogin(params)
    }
    
    // 清除登录失败次数
    uni.removeStorageSync('login_fail_count')
    
    // 登录成功提示
    showToast('登录成功')
    
    // 跳转到目标页面
    setTimeout(() => {
      const redirectUrl = uni.getStorageSync('auth_redirect_url')
      if (redirectUrl) {
        uni.removeStorageSync('auth_redirect_url')
        uni.reLaunch({ url: redirectUrl })
      } else {
        uni.switchTab({ url: '/pages/index/index' })
      }
    }, 1500)
    
  } catch (error: unknown) {
    // 错误处理
    if (error instanceof AuthError || error instanceof HttpError) {
      showToast(error.message, 'error')
      
      // 记录失败次数
      if (loginType.value === 'account') {
        const failCount = (uni.getStorageSync('login_fail_count') || 0) + 1
        uni.setStorageSync('login_fail_count', failCount)
        
        // 失败3次显示验证码
        if (failCount >= 3) {
          showCaptcha.value = true
          refreshCaptcha()
        }
      }
      
      // 刷新验证码
      if (showCaptcha.value) {
        refreshCaptcha()
      }
    } else {
      console.error('登录错误:', error)
      showToast('登录失败，请稍后重试', 'error')
    }
  } finally {
    loading.value = false
  }
}

// 发送验证码
const sendCode = async () => {
  if (!mobileForm.mobile || codeDisabled.value) return
  
  // 验证手机号
  if (!/^1[3-9]\d{9}$/.test(mobileForm.mobile)) {
    showToast('请输入正确的手机号')
    return
  }
  
  try {
    codeDisabled.value = true
    
    // 发送验证码请求
    await http.post('/api/auth/send-code', {
      mobile: mobileForm.mobile,
      type: 'login'
    })
    
    showToast('验证码已发送')
    
    // 倒计时
    let countdown = 60
    codeText.value = `${countdown}s`
    
    codeTimer.value = setInterval(() => {
      countdown--
      if (countdown <= 0) {
        clearInterval(codeTimer.value)
        codeText.value = '获取验证码'
        codeDisabled.value = false
      } else {
        codeText.value = `${countdown}s`
      }
    }, 1000) as unknown as number
    
  } catch (error: unknown) {
    codeDisabled.value = false
    console.error('发送验证码失败:', error)
    showToast('发送验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  captchaId.value = Date.now().toString()
  captchaUrl.value = `${http.baseURL}/api/auth/captcha?id=${captchaId.value}&t=${Date.now()}`
}

// 忘记密码
const handleForgetPassword = () => {
  uni.navigateTo({
    url: '/pages/auth/forget-password'
  })
}

// 注册
const handleRegister = () => {
  uni.navigateTo({
    url: '/pages/auth/register'
  })
}

// 第三方登录
const handleThirdPartyLogin = async (provider: 'wechat' | 'apple') => {
  showToast('功能开发中...')
}

// 显示提示
const showToast = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info') => {
  uToast.value.show({
    message,
    type,
    duration: 2000
  })
}

// 页面卸载时清理
onUnmounted(() => {
  if (codeTimer.value) {
    clearInterval(codeTimer.value)
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0 30rpx;
  
  .login-header {
    padding-top: 120rpx;
    text-align: center;
    
    .logo {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 40rpx;
    }
    
    .title {
      font-size: 48rpx;
      color: #fff;
      font-weight: bold;
    }
  }
  
  .login-form {
    margin-top: 80rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx 40rpx;
    box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.1);
    
    .login-tabs {
      display: flex;
      margin-bottom: 60rpx;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding-bottom: 20rpx;
        color: #999;
        font-size: 32rpx;
        position: relative;
        
        &.active {
          color: #667eea;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 4rpx;
            background: #667eea;
            border-radius: 2rpx;
          }
        }
      }
    }
    
    .form-item {
      margin-bottom: 40rpx;
      
      .captcha-img {
        width: 200rpx;
        height: 70rpx;
      }
    }
    
    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 60rpx;
      
      .remember-me {
        display: flex;
        align-items: center;
        
        .remember-text {
          margin-left: 10rpx;
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .forget-password {
        font-size: 28rpx;
        color: #667eea;
      }
    }
    
    .form-footer {
      text-align: center;
      margin-top: 40rpx;
      
      .register-link {
        font-size: 28rpx;
        color: #667eea;
      }
    }
    
    .third-party {
      margin-top: 80rpx;
      
      .divider {
        position: relative;
        text-align: center;
        margin-bottom: 40rpx;
        
        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          height: 1rpx;
          background: #e5e5e5;
        }
        
        .divider-text {
          position: relative;
          background: #fff;
          padding: 0 20rpx;
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .third-party-buttons {
        display: flex;
        justify-content: center;
        gap: 60rpx;
        
        .third-party-item {
          padding: 20rpx;
        }
      }
    }
  }
}
</style> 